package com.wave.controller;

import com.alibaba.fastjson.JSONObject;
import com.wave.entity.Deliver;
import com.wave.entity.LAF;
import com.wave.service.DeliverService;
import com.wave.service.LAFService;
import com.wave.service.UserService;
import com.wave.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/LAF")
public class LAFController {
    @Autowired
    private LAFService lafService;
    @Autowired
    private DeliverService deliverService;
    @Autowired
    private UserService userService;

    @PostMapping("create")
    public int createLAF(@RequestBody JSONObject requestJson) {
        // System.out.println(requestJson);
        LAF laf = LAFController.analyseLAFJson(requestJson);
        // 时间
        Date dateTime = new Date();
        Timestamp timestamp = new Timestamp(dateTime.getTime()); //利用timestamp格式直接转换
        laf.setLafCreatedate(timestamp);

        System.out.println(laf.toString());
        return lafService.createLAF(laf);
    }

    @PostMapping("alter")
    public int alterLAF(@RequestBody JSONObject requestJson) {
        // System.out.println(requestJson);
        LAF laf = LAFController.analyseLAFJson(requestJson);
        // 编号
        int lafId = requestJson.getInteger("lafId");
        laf.setLafId(lafId);

        System.out.println(laf.toString());
        return lafService.alterLAF(laf);
    }
    // 解析启事Json
    public static LAF analyseLAFJson(JSONObject requestJson){
        LAF laf = new LAF();
        // 标题
        String title = requestJson.getString("title");
        laf.setLafTitle(title);
        // 时间
        Date dateTime = new Date();
        Timestamp timestamp = new Timestamp(dateTime.getTime()); //利用timestamp格式直接转换
        laf.setLafLastdate(timestamp);
        // 正文内容
        String lafAddressDetail = requestJson.getString("addressDetail");   //详细位置
        String lafGoodsDetail = requestJson.getString("goodsDetail");       //物品描述
        String lafImgDetail =  requestJson.getString("imgDetail");
//        String lafImgDetail = "";
//        String imgUrl = "";
//        JSONArray lafImgDetailList = requestJson.getJSONArray("imgDetail"); //图片展示
//        for (int i = 0; i < lafImgDetailList.size(); i++){
//            imgUrl = (String)lafImgDetailList.get(i);
//            lafImgDetail = lafImgDetail + "<p><img src=\"" + imgUrl + "\" alt=\"图像\" width=\"100%\"></p><p><br></p>";
//        }
        String lafContactDetail = requestJson.getString("contactDetail");   //联系详细
        laf.setLafAddressDetail(lafAddressDetail);
        laf.setLafGoodsDetail(lafGoodsDetail);
        laf.setLafImgDetail(lafImgDetail);
        laf.setLafContactDetail(lafContactDetail);
        // 地址
        String address = requestJson.getString("address");
        laf.setLafAddress(address);
        // 联系方式
        String contact = requestJson.getString("contact");
        laf.setLafContact(contact);
        // 作者
        String author = requestJson.getString("author");
        laf.setLafAuthor(author);
        // 类型
        String type = requestJson.getString("lafType");
        laf.setLafType(type);
        // 状态
        laf.setLafState("1");
        // 头图
        String headImg = requestJson.getString("headImg");
        laf.setLafHeadImg(headImg);
        return laf;
    }

    @PostMapping("changeState")
    public int changeState(@RequestBody JSONObject requestJson)  {
        int lafId = requestJson.getInteger("lafId");
        String state = requestJson.getString("state");
        System.out.println("更改启事："+lafId+"状态："+state);
        if (state.equals("4")){         // 取消启事，相关交付进入结束
            deliverService.changeLafDeliver(lafId, "6");
        }
        return lafService.alterLAFState(lafId, state);
    }

    @PostMapping("closeList")
    public boolean closeList(@RequestBody List<Integer> lafIdList)  {
        try{
            for (int lafId : lafIdList) {
                System.out.println("关停启事编号："+lafId);
                deliverService.changeLafDeliver(lafId, "6");
                lafService.alterLAFState(lafId, "4");
            }
            return true;
        }
        catch (Exception e){
            return false;
        }
    }

    @RequestMapping("searchTitle")
    public List<LAF> searchLAFTitle(@RequestBody JSONObject requestJson){
        String lafTitle = requestJson.getString("lafTitle");
        String title = "%" + lafTitle + "%";
        //System.out.println(title);
        return lafService.searchLAFTitle(title);
    }

    @RequestMapping("getDetail")
    public JSONObject getLAFDetail(@RequestBody JSONObject requestJson){
        int id = requestJson.getInteger("id");
        System.out.println("获得启事详情页编号："+id);
        LAF laf = lafService.getLAFDetail(id);
        String lafAuthorName = userService.getUserName(laf.getLafAuthor());
        System.out.println("获得启事作者："+lafAuthorName);
        String imgDetailListStr = laf.getLafImgDetail();
        imgDetailListStr = imgDetailListStr.substring(1,imgDetailListStr.length()-1);
        String[] imgDetailList = imgDetailListStr.split(",");
        JSONObject respond = new JSONObject();
        respond.put("lafDetail", laf);
        respond.put("lafAuthorName", lafAuthorName);  //用户名称
        respond.put("imgDetailList", imgDetailList);  //启事图片
        return respond;
    }

    @PostMapping("uploadImg")
    public JSONObject uploadImg(@RequestParam(value = "image") MultipartFile uploadFile) {
        // 每天一个文件夹保存图片
        Date date = new Date(); // 现在时间 (Fri Dec 10 03:01:12 CST 2021)
        DateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
        String dateString =  formatDate.format(date);
        String pathPart = "lafImage/" + dateString + "/";
        String pathName = "D:/springboot/" + pathPart;//存储文件的本地绝对路径
        File file = new File(pathName);
        file.mkdirs();
        String fileName = uploadFile.getOriginalFilename();//获取文件名（包括后缀）
        pathName = pathName + fileName;
        try {
            FileOutputStream fos = new FileOutputStream(pathName);
            fos.write(uploadFile.getBytes()); // 写入文件
            System.out.println("图片上传成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String uploadImgPath = "file/static/" + pathPart + fileName;
        JSONObject respond = new JSONObject();
        respond.put("path", uploadImgPath);

        return respond;
    }

    @PostMapping("getList")
    public List<LAF> getLAFList(@RequestBody JSONObject requestJson){
        int type = requestJson.getInteger("type");          //主要类型
        boolean isFirst = requestJson.getBoolean("pageFirst");//是否为第一页
        int pageSize = requestJson.getInteger("pageSize");//一页加载数
        int pageNum = requestJson.getInteger("pageNum");  //要加载的页码
        int pageStart = PageUtils.pagesCalculate(isFirst,pageSize,pageNum); //加载起始
        System.out.println("从"+pageStart+"加载"+pageSize+"-pageNum"+pageNum+"-type"+type+"-isFirst"+isFirst);

        List<LAF> returnList = lafService.getLAFList(type,pageStart,pageSize);
        return returnList;
    }

    @PostMapping("list")
    public JSONObject list(@RequestBody JSONObject requestJson){
        String type = requestJson.getString("type");      //类型
        String name = requestJson.getString("name");      //作者名
        String title = requestJson.getString("title");      //标题名
        int pageSize = requestJson.getInteger("pageSize");//一页加载数
        int pageNum = requestJson.getInteger("pageNum");  //要加载的页码
        return lafService.list(type, name, title, pageNum, pageSize);
    }

    @PostMapping("getMyLAF")
    public List<LAF> getMyLAF(@RequestBody JSONObject requestJson){
        String author = requestJson.getString("author");
        System.out.println(author+"用户获得启事");
        return lafService.getMyLAF(author);
    }

    @PostMapping("getLAF_Deliver")
    public List<Deliver> getLAFDeliver(@RequestBody JSONObject requestJson){
        int lafId = requestJson.getInteger("lafId");
        System.out.println(lafId+"启事查询相关交付");
        return deliverService.getLAFDeliver(lafId);
    }

    @PostMapping("getDeliverDetail")
    public Deliver getDeliverDetail(@RequestBody JSONObject requestJson){
        int id = requestJson.getInteger("dId");
        System.out.println(id+"交付详情");
        return deliverService.getDeliverDetail(id);
    }

    @PostMapping("createDeliver")
    public int createDeliver(@RequestBody JSONObject requestJson){
        int target = requestJson.getInteger("target");
        String targetState = lafService.getState(target);
        if (!targetState.equals("3") && !targetState.equals("4") ){
            Deliver deliver = new Deliver();
            deliver.setdTarget(target);
            String author = requestJson.getString("author");
            deliver.setdAuthor(author);     // 发起者
            String text = requestJson.getString("text");
            deliver.setdText(text);         // 描述文本
            String img = requestJson.getString("img");
            deliver.setdImg(img);           // 描述图片
            String type = "1";
            if (targetState.equals("2")){    //  启事交付中，后至的交付搁置
                type = "3";
            }
            deliver.setdType(type);         // 交付待确认
            Date dateTime = new Date();
            Timestamp timestamp = new Timestamp(dateTime.getTime()); //利用timestamp格式直接转换
            deliver.setdDate(timestamp);    // 时间

            deliver.toString();
            return deliverService.createDeliver(deliver);
        }
        // 启事结束，关闭交付
        return 0;
    }

    @PostMapping("submitDeliver")
    public int submitDeliver(@RequestBody JSONObject requestJson){
        int dId = requestJson.getInteger("dId");            //交付编号
        String type = requestJson.getString("type");        //交付改变状态
        String state = deliverService.getType(dId);             //交付原状态
        int lafId = deliverService.getDetailTarget(dId);        //交付目标启事
        System.out.println("交付"+dId+"从"+state+"到"+type);
        switch (type) {
            case "2":   // 交付被拒绝

                break;
            case "7":   // 交付主动取消
                if (!state.equals("4")) {   // 交付在进行中被主动取消
                    // 搁置交付恢复待确认
                    deliverService.otherDeliverChange(dId, "1");
                    lafService.alterLAFState(lafId, "1");       // 启事恢复持续中
                }                           // 交付在等待中被主动取消
                break;
            case "5":   // 交付成功完成
                deliverService.otherDeliverChange(dId, "6");    // 搁置交付进入失败结束
                lafService.alterLAFState(lafId, "3");           // 启事完成
                break;
            case "6":   // 交付失败结束
                deliverService.otherDeliverChange(dId, "1");    // 搁置交付恢复待确认
                lafService.alterLAFState(lafId, "1");           // 启事恢复持续中
                break;
            case "4":   // 交付同意
                deliverService.otherDeliverChange(dId, "3");    // 待确认交付进入搁置
                lafService.alterLAFState(lafId, "2");           // 启事进入中
                break;
        }

        return deliverService.alterDeliverType(dId, type);     //更新交付状态
    }

    @PostMapping("closeDeliver")
    public boolean closeDeliver(@RequestBody JSONObject requestJson)  {
        try{
            int dId = requestJson.getInteger("dId");            //交付编号
            int lafId = deliverService.getDetailTarget(dId);        //交付目标启事

            deliverService.otherDeliverChange(dId, "1");    // 搁置交付恢复待确认
            lafService.alterLAFState(lafId, "1");           // 启事恢复持续中
            deliverService.alterDeliverType(dId, "6");      //更新交付状态
            return true;
        }
        catch (Exception e){
            return false;
        }
    }

    @PostMapping("getMyDeliver")
    public List<Deliver> getMyDeliver(@RequestBody JSONObject requestJson){
        String author = requestJson.getString("author");
        System.out.println(author+"用户查询交付");
        return deliverService.getMyDeliver(author);
    }

    @PostMapping("delList")
    public JSONObject delList(@RequestBody JSONObject requestJson){
        String target = requestJson.getString("target");  //目标启事
        String name = requestJson.getString("name");      //作者名
        String type = requestJson.getString("type");      //作者名
        int pageSize = requestJson.getInteger("pageSize");//一页加载数
        int pageNum = requestJson.getInteger("pageNum");  //要加载的页码
        return deliverService.list(target, name, type, pageNum,  pageSize);
    }

    @RequestMapping("getIndexLaf")
    public List<LAF> getIndexLAF(){
        System.out.println("首页启事");
        return lafService.getIndexLAF();
    }
}
